<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="退料单号" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="outsource_material_return" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="退料人员">
          <el-input v-model="formData.orderName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="退料日期" prop="inDate">
          <el-date-picker
            v-model="formData.materialReturnTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="外协订单号" class="clickChoose" prop="outsourceOrderCode">
          <el-input v-model="formData.outsourceOrderCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseOrder"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="外协供应商">
          <el-input v-model="formData.supplierName" placeholder="暂无" disabled />
          <!-- <a
            class="clickChoose_button"
            @click.prevent="choosePeople"
          >
            <svg-icon icon-class="选择弹框" />
          </a> -->
        </el-form-item>
        <el-form-item label="关联单据" prop="associatedDocument">
          <el-input v-model="formData.associatedDocument" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.url"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="入库单" class="double enterWarehouseInvoices" prop="enterWarehouseInvoices">
          <!--          <el-tooltip placement="top">-->
          <!--            <div slot="content">-->
          <!--              选择生成将在提交后自动生成入库单-->
          <!--            </div>-->
          <!--            <div>-->
          <!--              <svg-icon icon-class="提示" />-->
          <!--            </div>-->
          <!--          </el-tooltip>-->
          <div class="main_enterWarehouseInvoices">
            <el-radio v-model="enterWarehouseInvoices" label="1">生成</el-radio>
            <el-radio v-model="enterWarehouseInvoices" label="0">不生成</el-radio>
            <span class="main_enterWarehouseInvoices_text">(选择生成将在提交后自动生成入库单)</span>
          </div>
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            maxlength="200"
            show-word-limit
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <!-- 订单明细 -->
        <div />
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column label="物料编码" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="formData.automaticCreate == '1'" label="可退数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="returnNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.canReturnNumber }}</span>
            </template></el-table-column>
          <el-table-column label="退料数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="returnNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.materialReturnNumber }}</span>
            </template></el-table-column>
          <el-table-column label="备注" width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span>
              <!-- <el-input v-model="scope.row.remark" placeholder="请输入" clearable /> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSave">保存</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, getInfoByConfigKey } from '@/api/outsourceManage/outsourceReturnMaterial'
import { detailList } from '@/api/outsourceManage/outsourceReturnMaterial'
import moment from 'moment'
import ChooseOrder from './ChooseOrder.vue'
import supplier from '../outsourceOrder/supplier'
import addOrderDetail from './chooseMaterial.vue'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    const validateWarning = (rule, value, callback) => {
      if (!this.enterWarehouseInvoices) {
        callback(new Error('是否生成入库单不能为空'))
      } else {
        callback()
      }
    }
    return {
      rawData: [],
      formData: {
        id: '',
        code: '',
        orderName: '',
        materialReturnTime: '',
        associatedDocument: '',
        supplierName: '',
        outsourceOrderId: '',
        outsourceOrderCode: '',
        fileName: '',
        fileRealName: '',
        url: '',
        remark: '',
        returnDetailList: [],
        enterWarehouseInvoices: '',
        status: '1'
      },
      enterWarehouseInvoices: '',
      tableHeight: '400',
      tableData: [],
      tableData2: [],
      selectionsAll1: [],
      selectionsAll2: [],
      tableDefaultRow: null,
      rules: {
        supplierName: [
          { required: true, message: '外协供应商不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: '退料单号不能为空', trigger: 'blur' }
        ],
        outsourceOrderCode: [
          { required: true, message: '外协订单号不能为空', trigger: 'change' }
        ],
        enterWarehouseInvoices: [
          { required: true, validator: validateWarning, trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    if (this.id) { // 有id就是编辑
      this.getInfo()
    } else {
      this.getInfoByConfigKey()
    }
    this.formData.orderName = this.$store.state.user.name
    this.formData.materialReturnBy = this.$store.state.user.userId
    this.formData.materialReturnTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    getList() {
      detailList({ outsourceOrderId: this.formData.outsourceOrderId }).then(res => {
        res.data.forEach(item => {
          item.handleId = item.id
          delete item.id
          delete item.remark
          item.materialReturnNumber = '0'
        })
        this.rawData = this.$deepClone(res.data)
        this.tableData = this.mergeData(res.data)
      })
    },
    chooseOrderCallBack(data) {
      this.rawData = []
      this.tableData = []
      this.formData.outsourceOrderCode = data.code
      this.formData.outsourceOrderId = data.id
      this.formData.supplierName = data.supplierName
      this.formData.outsourceSupplierId = data.outsourceSupplierInformationId
      this.getList()
    },
    chooseOrder() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: ChooseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            // selectedRow: this.listData,
            id: this.formData.outsourceOrderId ? this.formData.outsourceOrderId : ''
          } // props
        },
        area: ['1320px', '700px'],
        title: '选择外协订单号', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    getInfoByConfigKey() {
      getInfoByConfigKey('outsourceReturnMaterialStatus').then(res => {
        this.enterWarehouseInvoices = res.data.outsourceReturnMaterialStatus
      })
    },
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'url', data[2])
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    selectionChange2(rows) {
      this.selectionsAll2 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => {
          this.formData[key] = res.data[key]
        })
        this.enterWarehouseInvoices = this.formData.enterWarehouseInvoices
        this.rawData = this.$deepClone(this.formData.returnDetailList)
        this.tableData = this.mergeData(this.formData.returnDetailList)
      })
    },
    // 选择供应商
    choosePeople() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: supplier, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.listData,
            id: this.formData.outsourceSupplierId ? this.formData.outsourceSupplierId : ''
          } // props
        },
        area: ['880px', '700px'],
        title: '选择外协供应商', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 提交
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.rawData.filter(item => item.materialReturnNumber == 0).length > 0) {
            this.$message.warning('退料数量不能为空')
            return
          }
          this.formData.enterWarehouseInvoices = this.enterWarehouseInvoices
          this.formData.returnDetailList = this.rawData
          if (this.formData.returnDetailList.length == 0) {
            this.$message.warning('退料明细不能为空')
            return
          }
          addOrUpdate({ ...this.formData, status: '1' }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 保存
    onSave() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.enterWarehouseInvoices = this.enterWarehouseInvoices
          this.formData.returnDetailList = this.rawData
          // if (this.formData.returnDetailList.length <= 0) {
          //   this.$message.warning('请添加外协退料单明细')
          //   return
          // } else if (this.formData.returnDetailList.filter(item => !item.returnNumber).length > 0) {
          //   this.$message.warning('退料数量不能为空')
          //   return
          // } else if (this.formData.returnDetailList.filter(item => item.returnNumber && !this.SETTINGS.reg_no_zero.test(item.returnNumber)).length > 0) {
          //   this.$message.warning('退料数量未正确填写')
          //   return
          // }
          addOrUpdate({ ...this.formData, status: '0' }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    add() {
      if (!this.formData.outsourceOrderId) {
        this.$message.warning('请选择外协订单号')
        return
      }
      this.$layer.iframe({
        // // 弹框
        content: {
          content: addOrderDetail, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.rawData,
            outsourceOrderId: this.formData.outsourceOrderId
          } // props
        },
        area: ['1320px', '700px'],
        title: '选择外协退料单明细', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择供应商的回调
    chooseSupplier(row) {
      this.formData.supplierName = row.name
      this.formData.outsourceSupplierId = row.id
    },
    // 选择物料明细的回调
    showMaterial(data) {
      this.rawData = this.$deepClone(data)
      this.tableData = this.mergeData(data)
      console.log('22222', data)
      console.log('11111', this.mergeData(data))
      // row.forEach(item => {
      //   if (item.id == item.materialId) {
      //     item.id = ''
      //     delete item.id
      //     item.remark = ''
      //   }
      //   item.materialUnitLabel = item.materialUnitName
      // })
      // this.tableData = row
    },
    mergeData(data) {
      const resultMap = data.reduce((result, item) => {
        const { materialId, materialReturnNumber } = item
        if (!result[materialId]) {
          result[materialId] = { ...item }
        } else {
          result[materialId].materialReturnNumber = (Number(result[materialId].materialReturnNumber) + Number(materialReturnNumber)).toString()
        }
        return result
      }, {})

      return Object.values(resultMap)
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
      const tableData = new Set(this.tableData.map(item => item.materialId))
      this.rawData = this.rawData.filter(item => tableData.has(item.materialId))
    }
  }
}
</script>

<style lang="less" scoped>
.main_enterWarehouseInvoices {
  margin-left: 59px;
  .main_enterWarehouseInvoices_text {
    padding-left: 10px;
    color: #CCCCCC;
  }
}
.enterWarehouseInvoices {
  /deep/ .el-form-item__label {
    width: 80px !important;
    padding-right: 0px !important;
  }
  /deep/ .el-tooltip {
    padding-left: 5px;
      padding-right: 40px !important;

  }
  /deep/ .el-form-item__content {
    display: flex;
  }
  /deep/ .el-radio {
    line-height: 30px
  }
}
</style>
